if (!kwok) var kwok = {};
if (!kwok.downloadpanel) kwok.downloadpanel = {};

kwok.downloadpanel =
{
	/*
	 * Loads the poreferences.
	 */
	loadPrefs: function()
	{
		var disabled = document.getElementById("lbDisabled");
		var list = document.getElementById("lbVisible");
		var count = list.itemCount;
		var order = Components.classes["@mozilla.org/preferences-service;1"]
			.getService(Components.interfaces.nsIPrefService)
			.getBranch("extensions.downloadpanel.")
			.QueryInterface(Components.interfaces.nsIPrefBranch2)
			.getCharPref("visibleItems");
		
		var orderSplit = order.split(",");
		
		// move items from disabled to visible
		for (var i = 0; i < orderSplit.length; i++)
		{
			try
			{
				var cur = document.getElementById(orderSplit[i]);
				disabled.removeChild(cur);
				list.insertBefore(cur, null);
			}
			catch (e)
			{
				// ignore as it's probably a missing element
			}
		}
	},
	
	/*
	 * Saves the preferences.
	 */
	savePrefs: function()
	{
		var list = document.getElementById("lbVisible");
		var count = list.itemCount;
		var order = "";
		
		for (var i = 0; i < count; i++)
		{
			var elem = list.getItemAtIndex(i);
			order += elem.id + ",";
		}
		
		// save pref and remove trailing ','
		Components.classes["@mozilla.org/preferences-service;1"]
			.getService(Components.interfaces.nsIPrefService)
			.getBranch("extensions.downloadpanel.")
			.QueryInterface(Components.interfaces.nsIPrefBranch2)
			.setCharPref("visibleItems", order.substring(0, order.length - 1));
	},
	
	/*
	 * Moves an item up in the visible list.
	 */
	moveUp: function()
	{
		var list = document.getElementById("lbVisible");
		var idx = list.currentIndex;
		
		if (idx > 0)
		{
			list.insertBefore(list.selectedItem, list.getItemAtIndex(--idx));
			list.selectedIndex = idx;
		}
	},
	
	/*
	 * Moves an item down in the visible list.
	 */
	moveDown: function()
	{
		var list = document.getElementById("lbVisible");
		var idx = list.currentIndex;
		
		if (idx >= 0 && idx < list.itemCount - 1)
		{
			list.insertBefore(list.selectedItem, list.getItemAtIndex(++idx).nextSibling);
			list.selectedIndex = idx;
		}
	},
	
	/*
	 * Disabled -> visible.
	 */
	addItem: function()
	{
		var list = document.getElementById("lbVisible");
		var rem = document.getElementById("lbDisabled");
		
		var item = rem.selectedItem;
		
		if (item)
		{
			rem.removeChild(item);
			list.insertBefore(item, null);
		}
	},
	
	/*
	 * Visible >- disabled.
	 */
	removeItem: function()
	{
		var list = document.getElementById("lbVisible");
		var rem = document.getElementById("lbDisabled");
		
		var item = list.selectedItem;
		
		if (item)
		{
			list.removeChild(item);
			rem.insertBefore(item, null);
		}
	},
}

window.addEventListener("load", kwok.downloadpanel.loadPrefs, false);